package com.fearless.test20210429;

/*
    JUC
    模拟循环通知，A线程执行完通知B线程执行，B线程执行完通知C线程执行，C执行完通知A执行

 */


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test01 {
    public static void main(String[] args) {
        Source source = new Source();


        //定义三个线程
        new Thread(() -> {
            for (int i = 0; i <10 ; i++) {
                source.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i <10 ; i++) {
                source.printB();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i <10 ; i++) {
                source.printC();
            }
        }, "C").start();

    }

}



//资源类
class Source{

    private Integer count=1;

    private Lock lock=new ReentrantLock();
    Condition condition = lock.newCondition();


    void printA(){//count为1的时候，A执行
        lock.lock();
            try {
                while (count!=1){
                    //判断是否等待
                    condition.await();
                }
                System.out.println(Thread.currentThread().getName()+"执行");
                count=2;
                condition.signalAll();

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
    }


    void printB(){//count为2的时候，B执行
        lock.lock();
        try {
            while (count!=2){//判断是否等待
                condition.await();//进入等待队列，释放锁和执行权
            }

            System.out.println(Thread.currentThread().getName()+"执行");
            count=3;
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }


    }

    void printC(){//count为3的时候。C执行
        lock.lock();
        try {
            while (count!=3){//判断是否等待
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"执行");
            count=1;
            condition.signalAll();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }




    }
}



